package com.chenqi.tool.listview

import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*

/**
 * 作者: CQ
 * 日期: 2021-11-09
 * 说明: ListView适配器封装
 */
abstract class ListViewAdapter<T>(var listData : MutableList<T>, var context : Context) : BaseAdapter() {

    fun addData(listData : MutableList<T>, isRest : Boolean) {
        if (isRest) {
            this.listData.clear()
        }
        this.listData.addAll(listData)
        onRefresh(this.listData)
    }

    fun onRefresh(listData : MutableList<T>) {
        this.listData = listData
        notifyDataSetChanged()
    }

    protected var onItemClick : (T) -> Unit = {}

    fun setOnItemClickListener(onItemClick : (T) -> Unit) {
        this.onItemClick = onItemClick
    }

    override fun getCount() : Int {
        return if (listData.isNullOrEmpty()) 0 else listData.size
    }

    override fun getItem(position : Int) : T {
        return listData[position]
    }

    override fun getItemId(position : Int) : Long {
        return position.toLong()
    }

    override fun getView(position : Int, convertView : View?, parent : ViewGroup?) : View {
        val holder : ViewHolder
        var view = convertView
        if (view == null) {
            view = LayoutInflater.from(context).inflate(getLayoutId(), parent, false)
            holder = ViewHolder(view)
            view.tag = holder
        } else {
            holder = view.tag as ViewHolder
        }
        onShowItem(holder, position)
        return view!!
    }

    protected abstract fun getLayoutId() : Int

    protected abstract fun onShowItem(holder : ViewHolder, position : Int)
}

class ViewHolder(var itemView : View) {
    private var mViews : SparseArray<View> = SparseArray()

    /**
     * 获取view 可以装换成想要的控件，然后处理
     */
    fun getView(viewId : Int) : View {
        var view : View? = mViews.get(viewId)
        if (view == null) {
            view = itemView.findViewById(viewId)
            mViews.put(viewId, view)
        }
        return view!!
    }

    /**
     * 获取TextView
     */
    fun getTextView(viewId : Int) : TextView {
        return getView(viewId) as TextView
    }

    /**
     * 获取EditText
     */
    fun getEditText(viewId : Int) : EditText {
        return getView(viewId) as EditText
    }

    /**
     * 获取imageView
     */
    fun getImageView(viewId : Int) : ImageView {
        return getView(viewId) as ImageView
    }

    /**
     * 获取CheckBox
     */
    fun getCheckBox(viewId : Int) : CheckBox {
        return getView(viewId) as CheckBox
    }


    /**
     * 获取itemView
     */
    fun getRootView() : View {
        return itemView
    }
}